var MAX_TAGS = 10;

function rewriteFlash()
{
    var flash = $('flashMessage');
    
    if(!flash)
	return;
	
    var hide = new Element('div', {'class': 'flash-hide'}).update('[hide]');
    Event.observe(hide, 'click', hideFlash);
    flash.insertBefore(hide, flash.firstChild);
}

function hideFlash()
{
    new Effect.Fade('flashMessage');
}

var tags;

function vote(id, offset)
{
	if(offset != 'up' && offset != 'down')
	{
		return;
	}
	
	var url = CORE_URL + 'quotes/ajaxvote/' + id + '/' + offset;
	$('qmsg' + id).style.display = 'none';
	$('qwait' + id).style.display = 'block';
	new Ajax.Request(url, { onSuccess: onVote, onFailure: onVoteFailed }).quoteId = id;
}

function delquote(id)
{
	var url = CORE_URL + 'quotes/delete/' + id;
	$('qmsg' + id).style.display = 'none';
	$('qwait' + id).style.display = 'block';
	new Ajax.Request(url, { onSuccess: onDelete, onFailure: onVoteFailed }).quoteId = id;
}

function spamquote(id)
{
	var url = CORE_URL + 'quotes/spam/' + id;
	$('qmsg' + id).style.display = 'none';
	$('qwait' + id).style.display = 'block';
	new Ajax.Request(url, { onSuccess: onDelete, onFailure: onVoteFailed }).quoteId = id;
}

function onVote(response)
{
	var id = response.request.quoteId;
	var result = response.responseJSON;
	$('qwait' + id).style.display = 'none';
	var msg = $('qmsg' + id);
    	
    	if(typeof(result.score) != 'undefined')
    	{
		var score = result.score;
		var votes = result.votes;
    		
    		var quote = $('q' + id);
		quote.down('.quote-score').update(score);
		quote.down('.quote-vcount').update(votes);
		msg.update('Vote cast');
    	}
    	else if(typeof(result.errorMessage) != 'undefined' && result.errorMessage.indexOf('more than once') != -1)
    	{
	    msg.update('Already voted');
    	}
    	else
    	{
	    msg.update('Error');
    	}

	msg.style.display = 'block';
}

function onDelete(response)
{
	var id = response.request.quoteId;
    	var text = response.responseText;
	$('qwait' + id).style.display = 'none';
	var msg = $('qmsg' + id);
    	
    	if(text.indexOf('deleted') != -1)
    	{
	    new Effect.Fade('q' + id);
	}
	else if(text.indexOf('permissions') != -1)
	{
	    msg.update('Action forbidden');
	}
	else
	{
	    msg.update('Error');
	}

	msg.style.display = 'block';
}

function onVoteFailed(request)
{
    var id = response.request.quoteId;
    var msg = $('qmsg' + id);
    msg.update('Error');
    msg.style.display = 'block';
}

function installSearch()
{
    window.external.AddSearchProvider(CORE_URL + 'files/opensearch.xml');
}

function installTagTypeAhead()
{
    if($('quote-edit-tags') == null)
        return;
    
    new Ajax.Request(CORE_URL + 'quotes/tags/xml', {onSuccess: onTagArrival});
}

function onTagArrival(response)
{
    var doc = response.responseXML;
    var tagElements = doc.getElementsByTagName('tag');
    tags = new Array(tagElements.length);
    
    for(var i = 0; i < tagElements.length; i++)
    {
        var obj = new Object();
        obj.name = tagElements[i].getAttribute('name');
        obj.count = tagElements[i].getAttribute('count');
        tags[i] = obj;
    }
    
    Event.observe('quote-edit-tags', 'keyup', tagAutoComplete);
    
    var ul = new Element('ul', {'id': 'tag-popup', 'style': 'display: none'});
    $('content').appendChild(ul);
}

function tagAutoComplete(e)
{
    var tbox = $('quote-edit-tags');
    var key = e.keyCode;
    var text = tbox.value;
    var pos = text.lastIndexOf(' ');
    
    if(pos != -1)
        text = text.substring(pos + 1);

    if(text == '')
    {
        removeTagPopup(e);
        return;
    }

    var range = findSubtext(tags, text);
    
    if(range.start == -1)
        removeTagPopup(e);
    else
        displayTagPopup(range);
}

function removeTagPopup(e)
{
    $('tag-popup').style.display = 'none';
}

function displayTagPopup(range)
{
    var ul = $('tag-popup');

    if(range.end > range.start + MAX_TAGS)
        range.end = range.start + MAX_TAGS;
    
    if(range.end > tags.length)
	range.end = tags.length;
    
    var child;
    
    while(child = ul.firstChild)
    {
	ul.removeChild(child);
    }
    
    for(var i = range.start; i < range.end; i++)
    {
	var text = tags[i].name + ' (' + tags[i].count + ')';
	var li = new Element('li').update(text);
	Event.observe(li, 'click', onTagSelect);
        ul.appendChild(li);
    }
    
    var textPos = findPos($('quote-edit-tags'));
    ul.style.left = textPos.x + 'px';
    ul.style.top = textPos.y + textPos.offsetHeight + 'px';
    ul.style.display = 'block';
}

function findSubtext(tags, text)
{
    var retval = new Object();
    retval.start = -1;
    retval.end = tags.length;
    
    for(var i = 0; i < tags.length; i++)
    {
        if(tags[i].name.substring(0, text.length) == text)
        {
            retval.start = i;
            break;
        }
    }
    
    if(retval.start == -1)
        return retval;
    
    for(var i = retval.start + 1; i < tags.length; i++)
    {
        if(tags[i].name.substring(0, text.length) != text)
        {
            retval.end = i;
            break;
        }
    }
    
    return retval;
}

function onTagSelect(e)
{
    var li = e.element();
    var tag = li.firstChild.nodeValue.substring(0, li.firstChild.nodeValue.indexOf(' '));
    var tbox = $('quote-edit-tags');
    var pos = tbox.value.lastIndexOf(' ');
    
    tbox.value = tbox.value.substring(0, pos + 1) + tag + ' ';
    $('tag-popup').style.display = 'none';
    tbox.focus();
}

function findPos(obj)
{
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	
	var retval = new Object();
	retval.x = curleft;
	retval.y = curtop;
	return retval;
}

function hookPreview()
{
    var button = $('quote-edit-preview');
    
    if(button)
	Event.observe(button, 'click', onPreview);
}

function onPreview(e)
{
    new Ajax.Updater('quote-preview', CORE_URL + 'quotes/rawpreview', {'postBody': Form.serialize('quote-edit')});
    e.stop();
}

function onLoad()
{
    rewriteFlash();
    hookPreview();
    installTagTypeAhead();
}

Event.observe(window, 'load', onLoad);
